package cn.yh.register.hosp.riceiver;

import cn.yh.register.common.constant.MqConst;
import cn.yh.register.common.service.RabbitService;
import cn.yh.register.hosp.service.ScheduleService;
import cn.yh.register.model.hosp.Schedule;
import cn.yh.register.vo.msm.MsmVo;
import cn.yh.register.vo.order.OrderMqVo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class HospitalReceiver {
    @Autowired
    ScheduleService scheduleService;
    @Autowired
    RabbitService rabbitService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConst.QUEUE_ORDER,durable = "true"),//那个队列
            exchange = @Exchange(MqConst.EXCHANGE_DIRECT_ORDER),//绑定交换机
            key = MqConst.ROUTING_ORDER//指定的路由key
    ))
    public void receive(OrderMqVo orderMqVo, Message message, Channel channel){
        log.info("医院服务接收更新号源消息：{}",orderMqVo);
        Schedule schedule = null;
        Integer availableNumber=null;
        // 判断是预约挂号更新号源还是取消预约更新号源
        if (orderMqVo.getAvailableNumber() != null) {
            schedule = scheduleService.getById(orderMqVo.getScheduleId());
            // 预约挂号更新号源
            Integer reservedNumber = orderMqVo.getReservedNumber();
            availableNumber = orderMqVo.getAvailableNumber();
            schedule.setReservedNumber(reservedNumber);
        }else {
            // 取消预约更新号源
            String hosScheduleId = orderMqVo.getScheduleId();
            schedule = scheduleService.getSchedule(hosScheduleId);
            availableNumber = schedule.getAvailableNumber() + 1;
        }
        schedule.setAvailableNumber(availableNumber);
        // 更新号源
        scheduleService.updateSchedule(schedule);
        //发送短信到MQ 由短信服务消费
        MsmVo msmVo = orderMqVo.getMsmVo();
        if (msmVo != null) {
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM,MqConst.ROUTING_MSM_ITEM,msmVo);
            log.info("医院服务发送短信通知消息：{}",msmVo);
        }

    }
}
